package com.cyandpos.pad.offline.model;

import android.content.ContentValues;
import android.database.Cursor;

import com.cyandpos.pad.http.OkHttpUtils;
import com.cyandpos.pad.netdata.R_Addpay;
import com.cyandpos.pad.offline.offlinedb.CursorUtil;
import com.cyandpos.pad.offline.offlinedb.Sqldb;
import com.cyandpos.pad.posdata.Goods;
import com.cyandpos.pad.posdata.Member;
import com.cyandpos.pad.posdata.Payment;
import com.cyandpos.pad.posdata.Person;
import com.cyandpos.pad.posdata.SubTicketItem;
import com.cyandpos.pad.posdata.TicketInfo;
import com.cyandpos.pad.utils.log.MessageLog;
import com.google.gson.Gson;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class OfflinePay {

    public static void addPay(Sqldb sqldb, Map<String, Object> params, OkHttpUtils.ResultCallback callback){
        String clearPay=params.get("clearPay")+"";
        if(!"true".equals(clearPay)) {
            List<Goods> goodsList = OfflineSale.getGoodsList(sqldb, params);
            List<Payment> payItems = (List<Payment>) params.get("payList");
            BigDecimal payAmount = new BigDecimal(0);
            if (payItems != null) {
                for (Payment payment : payItems) {
                    payAmount = payAmount.add(new BigDecimal(payment.getPayAmount()));
                    ContentValues values = new ContentValues();
                    values.put("ORDERNO", params.get("orderNo") + "");
                    values.put("SKTNO", params.get("sktno") + "");
                    values.put("JLBH", CursorUtil.getJLBH() + "");
                    values.put("SKFS", payment.getPayCode() + "");
                    values.put("SKJE", payment.getPayAmount());
                    values.put("YYJE", "");
                    values.put("PAYGUID", "");
                    values.put("SKJE_BB", "");
                    values.put("HL", "");
                    boolean isInsert = sqldb.insert("ORDER_PAY", values);
                    MessageLog.writeLog("ORDER_PAY insert="+isInsert+"/values="+new Gson().toJson(values));
                    if (isInsert) {
                        boolean isDelete = sqldb.delete("ORDER_ITEM", "ORDERNO=?", new String[]{params.get("orderNo") + ""});
                        MessageLog.writeLog("ORDER_ITEM isDelete="+isDelete);
                        BigDecimal count = new BigDecimal(0);
                        BigDecimal price = new BigDecimal(0);
                        BigDecimal discount = new BigDecimal(0);
                        for (Goods goods : goodsList) {
                            count = count.add(new BigDecimal(goods.getSaleCount()));
                            price = price.add(new BigDecimal(goods.getSaleMoney()));
                            discount = discount.add(new BigDecimal(goods.getDiscount()));
                            ContentValues values1 = new ContentValues();
                            values1.put("ORDERNO", params.get("orderNo") + "");
                            values1.put("SKTNO", params.get("sktno") + "");
                            values1.put("JLBH", CursorUtil.getJLBH() + "");
                            values1.put("TCKT_INX", goods.getTicktInx());
                            values1.put("INX", goods.getTicktGoodsInx());
                            values1.put("DEPTID", goods.getDeptId());
                            values1.put("DEPTCODE", goods.getDeptCode());
                            values1.put("SP_ID", goods.getId());
                            values1.put("BARCODE", goods.getBarCode());
                            values1.put("LSDJ", goods.getPrice());
                            values1.put("XSSL", goods.getSaleCount());
                            values1.put("XSJE", goods.getSaleMoney());
                            values1.put("ZKJE", goods.getDiscount());
                            values1.put("CRMINX", "");
                            values1.put("GUID", goods.getGoodsGuid());
                            values1.put("INPUTCODE", goods.getInputCode());
                            values1.put("CODE", goods.getCode());
                            values1.put("YHJE", goods.getPreferentialMoney());
                            values1.put("MBYH", "0");
                            values1.put("JF", "0");
                            values1.put("STAMP", "0");
                            values1.put("YYY", goods.getPersonId());
                            values1.put("TCKT_INX_OLD", 0);
                            values1.put("INX_OLD", 0);
                            values1.put("CXSPBJ", "0");
                            values1.put("BGH", "");
                            values1.put("XSDD_JLBH", "");
                            values1.put("SPJX", "");
                            values1.put("ORDERNO_ORIGINAL", "");
                            values1.put("FDBH_ORIGINAL", 0);
                            boolean isInsert1 = sqldb.insert("ORDER_ITEM", values1);
                            MessageLog.writeLog("ORDER_ITEM insert="+isInsert1+"/values1="+new Gson().toJson(values1));
                        }

                        R_Addpay addpay = new R_Addpay();
                        addpay.setDecMoney("0.0");
                        addpay.setOverflowAmount("0.0");
                        addpay.setTotalDiscount(discount + "");
                        addpay.setTotalAmount(price.subtract(discount) + "");
                        if (price.subtract(discount).subtract(payAmount).doubleValue() >= 0) {
                            addpay.setAmountPayable((price.subtract(discount).subtract(payAmount)) + "");
                            addpay.setChangeAmount("0.0");
                        } else {
                            addpay.setAmountPayable("0.0");
                            addpay.setChangeAmount(payAmount.subtract(price) + "");
                        }
                        ContentValues valuesPOS = new ContentValues();
                        valuesPOS.put("STATUS", "3");
                        boolean isPos=sqldb.update("POS_ORDER", valuesPOS, "ORDERNO=?", new String[]{params.get("orderNo") + ""});
                        MessageLog.writeLog("POS_ORDER update="+isPos+"/valuesPOS="+new Gson().toJson(valuesPOS));
                        callback.onSuccess(CursorUtil.getOfflineBean(addpay));
                    } else {
                        callback.onFailure("收款方式明细保存失败！");
                    }
                }
            }
        }else{
            ContentValues valuesPOS = new ContentValues();
            valuesPOS.put("STATUS", "4");
            boolean isUpdate=sqldb.update("POS_ORDER", valuesPOS, "ORDERNO=?", new String[]{params.get("orderNo") + ""});
            MessageLog.writeLog("POS_ORDER update="+isUpdate+"/valuesPOS="+new Gson().toJson(valuesPOS));
            boolean isDelete = sqldb.delete("ORDER_PAY", "ORDERNO=?", new String[]{params.get("orderNo") + ""});
            if(isDelete) {
                R_Addpay addpay = new R_Addpay();
                addpay.setDecMoney("0.0");
                addpay.setOverflowAmount("0.0");
                addpay.setTotalDiscount("0.0");
                addpay.setTotalAmount("0.0");
                addpay.setAmountPayable("0.0");
                addpay.setChangeAmount("0.0");
                callback.onSuccess(CursorUtil.getOfflineBean(addpay));
            }else{
                callback.onFailure("收款方式明细删除失败！");
            }
        }
    }

    public static void commitPay(Sqldb sqldb, Map<String, Object> params, OkHttpUtils.ResultCallback callback){
        SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date(System.currentTimeMillis());
        BigDecimal price=new BigDecimal(0);
        BigDecimal count=new BigDecimal(0);
        BigDecimal saleMoney=new BigDecimal(0);
        BigDecimal discount=new BigDecimal(0);
        String personId="";
        List<Goods> goodsList= OfflineSale.getGoodsList(sqldb,params);
        for(Goods g:goodsList){
            count=count.add(new BigDecimal(g.getSaleCount()));
            saleMoney=saleMoney.add(new BigDecimal(g.getSaleMoney()));
            discount=discount.add(new BigDecimal(g.getDiscount()));
        }

        List<Payment> payList=new ArrayList<>();
        try {
            Cursor cursor = sqldb.find("select A.ORDERNO,A.SKFS,A.SKJE,A.YYJE,A.PAYGUID,B.NAME from ORDER_PAY A,SKFS B where A.SKFS=B.CODE and A.ORDERNO="+"'"+params.get("orderNo")+"'");
            MessageLog.writeLog("select A.ORDERNO,A.SKFS,A.SKJE,A.YYJE,A.PAYGUID,B.NAME from ORDER_PAY A,SKFS B where A.SKFS=B.CODE and A.ORDERNO="+params.get("orderNo"));
            if (cursor != null && cursor.getCount() > 0) {
                while (cursor.moveToNext()) {
                        Payment payment = new Payment();
                        payment.setPayCode(Integer.parseInt(CursorUtil.getString(cursor, "SKFS")));
                        payment.setPayName(CursorUtil.getString(cursor, "NAME"));
                        payment.setPayAmount(CursorUtil.getString(cursor, "SKJE"));
                        payList.add(payment);
                        price = price.add(new BigDecimal(payment.getPayAmount()));
                }
                cursor.close();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        TicketInfo ticketInfo=new TicketInfo();
        ticketInfo.setCent("0");
        ticketInfo.setSktno(params.get("sktno")+"");
        ticketInfo.setJlbh(CursorUtil.getJLBH()+"");
        ticketInfo.setOrderNo(params.get("orderNo")+"");
        ticketInfo.setStoreCode(params.get("storeCode")+"");
        ticketInfo.setTotalCount(count.intValue()+"");
        ticketInfo.setTotalAmount(price+"");
        ticketInfo.setTotalDiscount(discount+"");
        ticketInfo.setDecMoney("0.0");
        ticketInfo.setDecPreferentialMoney("0.0");
        ticketInfo.setChangeAmount((price.add(discount).subtract(saleMoney))+"");
        ticketInfo.setOverflowAmount("0.0");
        ticketInfo.setNeedBuyCent(false);
        ticketInfo.setNeedVipToOfferCoupon(false);
        ticketInfo.setOrderTime(simpleDateFormat2.format(date));
        ticketInfo.setPayList(payList);

        Cursor cursorMember = sqldb.find("select * from ORDER_MEM where ORDERNO="+"'"+params.get("orderNo")+"'");
        MessageLog.writeLog("select * from ORDER_MEM where ORDERNO="+params.get("orderNo"));
        if(cursorMember!=null&&cursorMember.getCount()>0){
            while (cursorMember.moveToNext()){
                Member member=new Member();
                member.setMemberCardNo(CursorUtil.getString(cursorMember,"HYKNO"));
                member.setMemberCardTypeId(CursorUtil.getInt(cursorMember,"HYKTYPE"));
                ticketInfo.setMemberInfo(member);
            }
        }

        List<SubTicketItem> subTickets=new ArrayList<>();
        SubTicketItem subTicketItem=new SubTicketItem();
        subTicketItem.setGoodsList(goodsList);
        subTicketItem.setTcktInx("0");
        if(goodsList!=null&&goodsList.size()>0) {
            subTicketItem.setDeptCode(goodsList.get(0).getDeptCode());
            personId=goodsList.get(0).getPersonId();
        }

        try {
            Cursor cursorP = sqldb.find("select R.PERSON_ID,R.PERSON_NAME,R.DEPTID,R.WORK_TYPE,R.RYDM,B.BMDM,B.DEPT_NAME,R.SHOPID from RYXX R,BM B  where R.DEPTID=B.DEPTID  and (B.FDBH=" + "'"+params.get("storeCode") + "'"+" or B.FDBH=-1) and R.STATUS=1 AND R.PERSON_ID=" + personId + "  and (B.FDBH=" + "'"+params.get("storeCode") + "'"+" or B.FDBH=-1) and R.STATUS=1");
            MessageLog.writeLog("select R.PERSON_ID,R.PERSON_NAME,R.DEPTID,R.WORK_TYPE,R.RYDM,B.BMDM,B.DEPT_NAME,R.SHOPID from RYXX R,BM B  where R.DEPTID=B.DEPTID  and (B.FDBH=" + params.get("storeCode") + " or B.FDBH=-1) and R.STATUS=1 AND R.PERSON_ID=" + personId + "  and (B.FDBH=" + params.get("storeCode") + " or B.FDBH=-1) and R.STATUS=1");
            if (cursorP != null && cursorP.getCount() > 0) {
                while (cursorP.moveToNext()) {
                    Person person = new Person();
                    person.setPersonId(CursorUtil.getInt(cursorP, "PERSON_ID"));
                    person.setPersonName(CursorUtil.getString(cursorP, "PERSON_NAME"));
                    person.setPersonCode(CursorUtil.getString(cursorP, "RYDM"));
                    person.setPersonDeptId(CursorUtil.getInt(cursorP, "DEPTID"));
                    person.setPersonDeptCode(CursorUtil.getString(cursorP, "BMDM"));
                    person.setPersonDeptName(CursorUtil.getString(cursorP, "DEPT_NAME"));
                    person.setShopId(CursorUtil.getInt(cursorP, "SHOPID"));
                    subTicketItem.setPersonInfo(person);
                }
                cursorP.close();
            }
        }catch (Exception e){
            e.printStackTrace();
            MessageLog.writeLog(e+"");
        }
        subTickets.add(subTicketItem);
        ticketInfo.setSubTickets(subTickets);
        try {
            Cursor cursorOrder = sqldb.find("select ORDERNO,SKTNO,JLBH,FDBH,JYLX,DDLY,KSSJ,SKY,XSJE,STATUS,JYJF,OLDORDERNO from POS_ORDER where ORDERNO="+"'"+params.get("orderNo")+"'");
            MessageLog.writeLog("select ORDERNO,SKTNO,JLBH,FDBH,JYLX,DDLY,KSSJ,SKY,XSJE,STATUS,JYJF,OLDORDERNO from POS_ORDER where ORDERNO="+params.get("orderNo"));
            if (cursorOrder != null && cursorOrder.getCount() > 0) {
                while (cursorOrder.moveToNext()) {
                        int personID= CursorUtil.getInt(cursorOrder, "SKY");
                        Cursor cursorPerson = sqldb.find("select R.PERSON_ID,R.PERSON_NAME,R.DEPTID,R.WORK_TYPE,R.RYDM,B.BMDM,B.DEPT_NAME,R.SHOPID from RYXX R,BM B  where R.DEPTID=B.DEPTID AND  R.PERSON_ID=" + personID + " and (B.FDBH=" + "'"+params.get("storeCode") + "'"+" or B.FDBH=-1) and R.STATUS=1");
                        if (cursorPerson != null && cursorPerson.getCount() > 0) {
                            while (cursorPerson.moveToNext()) {
                                Person person = new Person();
                                person.setPersonId(CursorUtil.getInt(cursorPerson, "PERSON_ID"));
                                person.setPersonName(CursorUtil.getString(cursorPerson, "PERSON_NAME"));
                                person.setPersonCode(CursorUtil.getString(cursorPerson, "RYDM"));
                                person.setPersonDeptId(CursorUtil.getInt(cursorPerson, "DEPTID"));
                                person.setPersonDeptCode(CursorUtil.getString(cursorPerson, "BMDM"));
                                person.setPersonDeptName(CursorUtil.getString(cursorPerson, "DEPT_NAME"));
                                ticketInfo.setCasherInfo(person);
                            }
                        }
                }
                cursorOrder.close();
            }
        }catch (Exception e){
            e.printStackTrace();
            MessageLog.writeLog(e+"");
        }

        distributionAmount(payList,goodsList,sqldb,params);

        updateOrderPerson(sqldb,params);

        updatePosOrder(sqldb,params,simpleDateFormat2.format(date),price+"",simpleDateFormat2.format(date),new BigDecimal(ticketInfo.getChangeAmount())+"");

        insertPos_tjsc(sqldb,params);

        callback.onSuccess(CursorUtil.getOfflineBean(ticketInfo));
    }

    /**
     * 分销金额
     */
    public static void distributionAmount(List<Payment> payList, List<Goods> goodsList, Sqldb sqldb, Map<String, Object> params){

        Collections.sort(goodsList, new Comparator<Goods>() {

            @Override
            public int compare(Goods goods1, Goods goods2) {
                // TODO Auto-generated method stub
                //定义比较大小
                if(new BigDecimal(goods1.getSaleMoney()).subtract(new BigDecimal(goods1.getDiscount())).doubleValue() > new BigDecimal(goods2.getSaleMoney()).subtract(new BigDecimal(goods2.getDiscount())).doubleValue() )
                {
                    return 1;
                }
                else if(new BigDecimal(goods1.getSaleMoney()).subtract(new BigDecimal(goods1.getDiscount())).doubleValue() == new BigDecimal(goods2.getSaleMoney()).subtract(new BigDecimal(goods2.getDiscount())).doubleValue() )
                {
                    return 0;
                }
                else
                {
                    return -1;
                }
            }
        });

        String index="";
        for(Payment payment:payList) {
            BigDecimal payAmount=new BigDecimal(payment.getPayAmount());
            BigDecimal item=new BigDecimal(0);
            if(goodsList.size()!=0){
                 item= payAmount.divide(new BigDecimal(goodsList.size()));
            }
            for(int i=0;i<goodsList.size();i++) {
                if(!index.contains(i+"")) {
                    ContentValues values1 = new ContentValues();
                    if(i!=goodsList.size()-1) {
                        if (new BigDecimal(goodsList.get(i).getSaleMoney()).subtract(new BigDecimal(goodsList.get(i).getDiscount())).doubleValue() <= item.doubleValue()) {
                            index = index + i;
                            payAmount = payAmount.subtract(new BigDecimal(goodsList.get(i).getSaleMoney()).subtract(new BigDecimal(goodsList.get(i).getDiscount())));
                            values1.put("SKJE", new BigDecimal(goodsList.get(i).getSaleMoney()).subtract(new BigDecimal(goodsList.get(i).getDiscount()))+"");
                        } else {
                            values1.put("SKJE", item+"");
                            payAmount = payAmount.subtract(item);
                        }
                    }else{
                        values1.put("SKJE", payAmount+"");
                    }

                    values1.put("ORDERNO", params.get("orderNo") + "");
                    values1.put("SKTNO", params.get("sktno") + "");
                    values1.put("JLBH", CursorUtil.getJLBH());
                    values1.put("TCKT_INX", goodsList.get(i).getTicktInx());
                    values1.put("INX", goodsList.get(i).getTicktGoodsInx());
                    values1.put("DEPTID", goodsList.get(i).getDeptId());
                    values1.put("SP_ID", goodsList.get(i).getId());
                    values1.put("GUID", goodsList.get(i).getGoodsGuid());
                    values1.put("SKFS", payment.getPayCode());
                    boolean isInsert=sqldb.insert("ORDER_ITEM_PAY", values1);
                    MessageLog.writeLog("ORDER_ITEM_PAY insert="+isInsert+"/values1="+new Gson().toJson(values1));
                }
            }
        }
    }

    /**
     * 更新ORDER_PERSON表
     */
    public static void updateOrderPerson(Sqldb sqldb,Map<String, Object> params){
        ContentValues valuesPerson=new ContentValues();
        valuesPerson.put("JLBH", CursorUtil.getJLBH());
        boolean isUpdate=sqldb.update("ORDER_PERSON",valuesPerson,"ORDERNO=?", new String[]{params.get("orderNo") + ""});
        MessageLog.writeLog("ORDER_PERSON update="+isUpdate+"/valuesPerson="+new Gson().toJson(valuesPerson));
    }

    /**
     * 更新POS_ORDER表
     */
    public static void updatePosOrder(Sqldb sqldb,Map<String, Object> params,String JSSJ,String XSJE,String JZRQ,String ZLJE){
        ContentValues values = new ContentValues();
        values.put("JLBH", CursorUtil.getJLBH());
        values.put("JSSJ", JSSJ);
        values.put("STATUS","1");
        values.put("XSJE",XSJE);
        values.put("JZRQ", JZRQ);
        values.put("ZLJE", ZLJE);
        boolean isUpdate=sqldb.update("POS_ORDER", values, "ORDERNO=?", new String[]{params.get("orderNo") + ""});
        MessageLog.writeLog("POS_ORDER update="+isUpdate+"/values="+new Gson().toJson(values));
    }

    /**
     * 添加脱机上传表
     */
    public static void insertPos_tjsc(Sqldb sqldb,Map<String, Object> params){
        boolean isDelete = sqldb.delete("POS_TJSC", "ORDERNO=?", new String[]{params.get("orderNo") + ""});
        ContentValues values = new ContentValues();
        values.put("ORDERNO", params.get("orderNo")+"");
        values.put("FDBH", Integer.parseInt(params.get("storeCode")+""));
        values.put("SKTNO",params.get("sktno")+"");
        values.put("JLBH", CursorUtil.getJLBH());
        values.put("FSCS", 0);
        values.put("BJ", 0);
        boolean isInsert=sqldb.insert("POS_TJSC", values);
        MessageLog.writeLog("POS_TJSC insert="+isInsert+"/values="+new Gson().toJson(values));
    }
}
